package com.crcc.common.util;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class imageUtil {

    public static FileNameVO getFile(String url,String url2) {
        //对本地文件命名
        String fileName = url.substring(0,url.indexOf("."));
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            //注:这里的后缀可以根据你传入的url的图片类型后缀定义,
            //这里因为项目业务需求,回调是pdf,所以写死了
            file = File.createTempFile(fileName, ".jpg",new File(url2));
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        FileNameVO fileNameVO = new FileNameVO();
        fileNameVO.setFile(file);
        fileNameVO.setFileName(file.getName());
        return fileNameVO;
    }
    public static FileNameVO getFileXlsx(String url,String url2) {
        //对本地文件命名
        String fileName = url.substring(0,url.indexOf("."));
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            //注:这里的后缀可以根据你传入的url的图片类型后缀定义,
            //这里因为项目业务需求,回调是pdf,所以写死了
            file = File.createTempFile(fileName, ".xlsx",new File(url2));
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        FileNameVO fileNameVO = new FileNameVO();
        fileNameVO.setFile(file);
        fileNameVO.setFileName(file.getName());
        return fileNameVO;
    }
    public static FileNameVO getFileXls(String url,String url2) {
        //对本地文件命名
        String fileName = url.substring(0,url.indexOf("."));
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            //注:这里的后缀可以根据你传入的url的图片类型后缀定义,
            //这里因为项目业务需求,回调是pdf,所以写死了
            file = File.createTempFile(fileName, ".xls",new File(url2));
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        FileNameVO fileNameVO = new FileNameVO();
        fileNameVO.setFile(file);
        fileNameVO.setFileName(file.getName());
        return fileNameVO;
    }
    public static File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."));
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            //注:这里的后缀可以根据你传入的url的图片类型后缀定义,
            //这里因为项目业务需求,回调是pdf,所以写死了
            file = File.createTempFile("temp_image", fileName+".jpg");
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 获取文本长度。汉字为1:1，英文和数字为2:1
     */
    private static int getTextLength(String text) {
        int length = text.length();
        for (int i = 0; i < text.length(); i++) {
            String s = String.valueOf(text.charAt(i));
            if (s.getBytes().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }


    /**
     * 图片添加水印
     *
     * @param srcImgPath
     *            需要添加水印的图片的路径
     * @param markContentColor
     *            水印文字的颜色
     * @param waterMarkContent
     *            水印的文字
     */
    public static FileNameVO mark(String srcImgPath, Color markContentColor, String waterMarkContent,String url,String name)throws Exception {
        FileNameVO fv = imageUtil.getFile(srcImgPath,url);
        // 读取原图片信息
        Image srcImg = ImageIO.read(fv.getFile());
        int srcImgWidth = srcImg.getWidth(null);
        int srcImgHeight = srcImg.getHeight(null);
        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        // Font font = new Font("Courier New", Font.PLAIN, 12);
        Font font = new Font("宋体", Font.PLAIN, 20);
//            g.setColor(markContentColor); // 根据图片的背景设置水印颜色
//
//            g.setFont(font);
//            int x = srcImgWidth - getWatermarkLength(waterMarkContent, g) - 3;
//            int y = srcImgHeight - 3;
//            // 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
//            // int x = (srcImgWidth - getWatermarkLength(watermarkStr, g)) / 2;
//            // int y = srcImgHeight / 2;
//            g.drawString(waterMarkContent, x,y);
        // 设置水印文字颜色
        g.setColor(markContentColor);
        // 设置水印文字Font
        g.setFont(font);
        // 设置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));

        int x = -srcImgWidth / 2;
        int y = -srcImgHeight / 2;
        int markWidth = 20 * getTextLength(waterMarkContent);// 字体长度
        int markHeight = 20;// 字体高度

        // 循环添加水印
        while (x < srcImgWidth * 1.5) {
            y = -srcImgHeight / 2;
            while (y < srcImgHeight * 1.5) {
                g.drawString(waterMarkContent, x, y);

                y += markHeight + 80;
            }
            x += markWidth + 80;
        }

        g.dispose();
        // 输出图片

        File file =File.createTempFile(name, ".jpg",new File(url));
        FileOutputStream outImgStream = new FileOutputStream(file);
        ImageIO.write(bufImg, "jpg", outImgStream);
        outImgStream.flush();
        outImgStream.close();
        FileNameVO fileNameVO = new FileNameVO();
        fileNameVO.setFile(file);
        fileNameVO.setFileName(file.getName());
        fileNameVO.setFileNameNew(fv.getFileName());
        return fileNameVO;
    }


    /**
     * 图片添加水印
     *
     * @param srcImgPath
     *            需要添加水印的图片的路径
     * @param markContentColor
     *            水印文字的颜色
     * @param waterMarkContent
     *            水印的文字
     */
    public static void mark1(String srcImgPath, Color markContentColor, String waterMarkContent,String iconPath)throws Exception {
        // 读取原图片信息
        Image srcImg = ImageIO.read(imageUtil.getFile(srcImgPath));
        int srcImgWidth = srcImg.getWidth(null);
        int srcImgHeight = srcImg.getHeight(null);
        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        // Font font = new Font("Courier New", Font.PLAIN, 12);
        Font font = new Font("宋体", Font.PLAIN, 20);
        // 设置水印文字颜色
        g.setColor(markContentColor);
        // 设置水印文字Font
        g.setFont(font);
        // 设置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
        int x = -srcImgWidth / 2;
        int y = -srcImgHeight / 2;
        int markWidth = 20 * getTextLength(waterMarkContent);// 字体长度
        int markHeight = 20;// 字体高度
        // 循环添加水印
        while (x < srcImgWidth * 1.5) {
            y = -srcImgHeight / 2;
            while (y < srcImgHeight * 1.5) {
                g.drawString(waterMarkContent, x, y);

                y += markHeight + 80;
            }
            x += markWidth + 80;
        }
        g.dispose();
        // 输出图片
        FileOutputStream outImgStream = new FileOutputStream(iconPath);
        ImageIO.write(bufImg, "jpg", outImgStream);

        outImgStream.flush();
        outImgStream.close();
    }

    public static void main(String[] args) {
        try {
            mark1("http://192.168.19.228:3443/group1/M03/09/BF/wKgT5GKNntqAEVAUAEqQkXblttE393.jpg",Color.lightGray,"中铁十九局集团有限公司","D:\\新建文件夹\\水印2.jpg");
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    /**
     * 获取水印文字总长度
     *
     * @param waterMarkContent
     *            水印的文字
     * @param g
     * @return 水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }



//    /**
//     * 给图片添加水印、可设置水印图片旋转角度
//     *
//     * @param iconPath
//     *            水印图片路径
//     * @param multiFile
//     *            multiFile
//     * @param degree
//     *            水印图片旋转角度
//     */
//    public static File markImageByIcon(String iconPath, String multiFile, Integer degree, String url) {
//        OutputStream os = null;
//        File file = null;
//        try {
//            Image srcImg = ImageIO.read(getFile(multiFile,url));
//            int srcImgWidth = srcImg.getWidth(null);
//            int srcImgHeight = srcImg.getHeight(null);
//            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null),
//                    BufferedImage.TYPE_INT_RGB);
//
//            // 得到画笔对象
//            // Graphics g= buffImg.getGraphics();
//            Graphics2D g = buffImg.createGraphics();
//
//            // 设置对线段的锯齿状边缘处理
//            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
//
//            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0,
//                    0, null);
//
//            if (null != degree) {
//                // 设置水印旋转
//                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
//            }
//
//            // 水印图象的路径 水印一般为gif或者png的，这样可设置透明度
//            ImageIcon imgIcon = new ImageIcon(getFile(iconPath,url).getPath());
//
//            // 得到Image对象。
//            Image img = imgIcon.getImage();
//
//            float alpha = 0.9f; // 透明度
//            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
//
//            // 表示水印图片的位置
//            g.drawImage(img, 80, 30, null);
//
//            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
//
//            g.dispose();
//
//            file =File.createTempFile(String.valueOf(new Date().getTime()), ".jpg");
//
//            os = new FileOutputStream(file);//写入源文件
//
//            // 生成图片
//            ImageIO.write(buffImg, "JPG", os);
//
//            //System.out.println("图片完成添加Icon印章。。。。。。");
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (null != os)
//                    os.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return file;
//    }

    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
